package com.kexilo.system.user.controller;

import com.kexilo.core.common.annotation.Debounce;
import com.kexilo.core.common.annotation.Idempotent;
import com.kexilo.core.common.annotation.Log;
import com.kexilo.core.common.constant.UserConstants;
import com.kexilo.core.common.core.web.BaseController;
import com.kexilo.core.common.core.web.domain.R;
import com.kexilo.core.common.enums.BusinessType;
import com.kexilo.core.common.utils.SecurityUtils;
import com.kexilo.core.common.utils.StringUtils;
import java.util.Arrays;

import com.kexilo.core.user.domain.SysDept;
import com.kexilo.system.user.service.ISysDeptService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 部门信息
 * 
 * @author Kexilo
 */
@RestController
@RequestMapping("/system/dept")
@Tag(name = "部门管理", description = "部门信息管理相关接口")
public class SysDeptController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(SysDeptController.class);
    
    @Autowired
    private ISysDeptService deptService;
    
    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    @Operation(summary = "获取部门列表", description = "获取部门列表信息")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "403", description = "权限不足")
    })
    public R<List<SysDept>> list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(depts);
    }
    
    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    @Operation(summary = "查询部门列表（排除节点）", description = "获取部门列表，排除指定节点及其子节点")
    public R<List<SysDept>> excludeChild(@Parameter(description = "部门ID") @PathVariable Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId || Arrays.asList(StringUtils.split(d.getAncestors(), ",")).contains(deptId + "")) {
                it.remove();
            }
        }
        return success(depts);
    }
    
    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    @Operation(summary = "获取部门详情", description = "根据部门ID获取部门详细信息")
    public R<SysDept> getInfo(@Parameter(description = "部门ID") @PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.selectDeptById(deptId));
    }
    
    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    @Operation(summary = "获取部门下拉树列表", description = "获取部门树形结构数据")
    public R<List<Object>> treeselect(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(deptService.buildDeptTreeSelect(depts));
    }
    
    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    @Operation(summary = "加载对应角色部门列表树", description = "获取角色对应的部门树结构")
    public R<Map<String, Object>> roleDeptTreeselect(@Parameter(description = "角色ID") @PathVariable("roleId") Long roleId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        result.put("depts", deptService.buildDeptTreeSelect(depts));
        return success(result);
    }
    
    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @Debounce(strategy = Debounce.Strategy.REQUEST_PARAMS, interval = 5, message = "请勿重复提交部门信息")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#dept.deptName + ':' + #dept.parentId", timeout = 5, message = "该部门正在处理中，请稍后再试")
    @PostMapping
    @Operation(summary = "新增部门", description = "新增部门信息")
    public R<Void> add(@Validated @RequestBody SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }
    
    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @Debounce(strategy = Debounce.Strategy.REQUEST_PARAMS, interval = 3, message = "请勿频繁修改部门信息")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#dept.deptId", timeout = 3, message = "部门信息正在更新中，请稍后再试")
    @PutMapping
    @Operation(summary = "修改部门", description = "修改部门信息")
    public R<Void> edit(@Validated @RequestBody SysDept dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }
    
    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @Debounce(strategy = Debounce.Strategy.USER_METHOD, interval = 5, message = "删除操作过于频繁，请稍后再试")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#deptId", timeout = 5, delKey = true, message = "删除操作正在进行中，请勿重复操作")
    @DeleteMapping("/{deptId}")
    @Operation(summary = "删除部门", description = "删除部门信息")
    public R<Void> remove(@Parameter(description = "部门ID") @PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return error("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }
}
